package com.bbcare.followup.plat.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.QueryModel;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.service.IPatientQueueService;
import com.bbcare.followup.plat.service.IPatientService;

/**
 * 患者队列信息操作类
 * @author tao
 *
 */
@Controller
@RequestMapping("/service/patient")
public class QueuePatientController {
    private final Log logger = LogFactory.getLog(QueuePatientController.class);

    @Autowired
    private IPatientQueueService patientQueueService;

    @Autowired
    private IPatientService patientSerivce;

    /**
     * 患者队列切换  ，修改原来队列患者信息 置为 已转移 ， 新建新的队列患者信息
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/queueTransfer")
    public ResultModel<HashMap<String, Object>> patientQueueTransfer(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in patientQueueTransfer----arg==" + arg.toString());
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String fromQueueId = requestParam.getString("fromQueueId");
        String toQueueId = requestParam.getString("toQueueId");
        String userId = requestParam.getString("userId");
        String queueSchemeId = requestParam.getString("queueSchemeId");
        if(StringUtils.isEmpty(fromQueueId)||StringUtils.isEmpty(toQueueId)
        		||StringUtils.isEmpty(userId)||StringUtils.isEmpty(queueSchemeId)){
        	logger.debug("out patientQueueTransfer----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
        			"参数校验失败，原队列ID|新队列ID|患者ID|原患者队列ID都不能为空");
        }

        HashMap<String, Object> paramPamp = new HashMap<String, Object>();

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");
        String tenantId = (String)sessionMap.get("tenantId");// 租户id
//        String deptId = (String) sessionMap.get("rootGroupId");// 科室id

        // 创建时间
        String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
        paramPamp.put("queueId", toQueueId);
        paramPamp.put("updateTime", currTime);
        paramPamp.put("authorId", authorId);
        paramPamp.put("authorName", authorName);
        paramPamp.put("updateAccept", updateAccept);
        paramPamp.put("fromQueueId", fromQueueId);
        paramPamp.put("fromQueueSchemeId", queueSchemeId);
//        paramPamp.put("userId", userId);
        paramPamp.put("tenantId", tenantId);

        paramPamp.put("opCode", Constants.OP_CODE_1004);
        paramPamp.put("opType", "3");

        Map<String, Object> paramTemp = new HashMap<String, Object>();
        paramTemp.put("userId", userId);
//        paramTemp.put("status", 1);

        Patient patient =  patientSerivce.getPatient(paramTemp);
        if(null == patient){
        	logger.debug("out patientQueueTransfer----patient== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,
        			"患者信息不存在");
        }

        paramPamp.put("patient", patient);
        patientSerivce.registerPatient(paramPamp);

//        patientQueueService.queuePatientTransfer(paramPamp);
        HashMap<String, Object> userMap = new HashMap<String, Object>();

        logger.warn("out patientQueueTransfer----userMap==" + userMap.toString());

        return new ResultModel<HashMap<String, Object>>(userMap);
    }

    // 队列患者恢复、暂停操作
    @ResponseBody
    @RequestMapping("/queueOperation")
    public ResultModel<Object> queuePatientOperation(@RequestBody String arg, HttpServletRequest request) throws Exception{
    	logger.info("in queuePatientOperation----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		String userId = requestParam.getString("userId");
        String queueSchemeId = requestParam.getString("queueSchemeId");
        String opCode = requestParam.getString("opCode");
        if(StringUtils.isEmpty(queueSchemeId)||StringUtils.isEmpty(opCode)){
        	logger.debug("out queuePatientOperation----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
        			"参数校验失败，队列患者ID|患者ID都不能为空");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");
        String tenantId = (String)sessionMap.get("tenantId");// 租户id

        Map<String, Object> paramTemp = new HashMap<String, Object>();
        paramTemp.put("userId", userId);
        paramTemp.put("tenantId", tenantId);

        Patient patient =  patientSerivce.getPatient(paramTemp);
        if(null == patient){
        	logger.debug("out patientQueueTransfer----patient== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,
        			"患者信息不存在");
        	}

        requestParam.put("userName", patient.getUserName());
        requestParam.put("updateAccept", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID));
        requestParam.put("authorName", authorName);
        requestParam.put("authorId",authorId);
        patientQueueService.queuePatientModify(requestParam);

    	return new ResultModel<Object>(null);
    }

    /**
     * 队列暂停患者列表查询  针对某一特定队列
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/queueStopPatientQuery")
    public QueryModel<Map<String, Object>>  queueStopPatientList(@RequestBody String arg, HttpServletRequest request) throws Exception{
    	logger.info("in queueStopPatientList----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String queueId = requestParam.getString("queueId");
        if(StringUtils.isEmpty(queueId)){
        	logger.debug("out queuePatientOperation----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "患者队列ID不能为空");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");

        requestParam.put("authorId",authorId);
        requestParam.put("tenantId",tenantId);
        Map<String,Object> param =  new HashMap<String,Object>();
//        patientQueueService.queuePatientModify(requestParam);
        param.putAll(requestParam);
        List<Map<String,Object>> list = patientQueueService.getQueueStopPatientList(param);
        int total = patientQueueService.getQueueStopPatientCount(param);
    	return new QueryModel<Map<String, Object>>(list, total);
    }

}
